<!--
 * @Author: huyuhang
 * @Data: 
 * @LastEditors: huyuhang
 * @LastEditTime: 2024-04-11 10:31:37
 * @Description: 文件服务器数据源管理
-->
<template>
  <div class="file-server">
    <ContentWrap>
      <el-form @submit.prevent label-width="110px" :model="searchValue" ref="formRef">
        <el-row>
          <el-col :span="6">
            <el-form-item label="数据源名称" prop="name">
              <ns-input
                v-model="searchValue.name"
                clearable
                placeholder="请输入数据源名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="6">
            <el-form-item label="资产IP" prop="ip">
              <ns-input v-model="searchValue.ip" clearable placeholder="请输入资产IP" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="资产类型" prop="assetType">
              <el-select v-model="searchValue.assetType" clearable placeholder="请选择资产类型">
                <el-option
                  v-for="item in assetTypeList"
                  :label="item.showName"
                  :key="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="归属机构" prop="deptId">
              <el-cascader
                v-model="searchValue.deptId"
                clearable
                placement="left"
                placeholder="请选择归属机构"
                :options="options"
                :props="cascaderProps"
                filterable
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="归属系统" prop="sysId">
              <el-cascader
                ref="systemCascader"
                v-model="searchValue.sysId"
                placeholder="请选择归属系统"
                :props="systemCascaderProps"
                :options="systemList"
                filterable
                clearable
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="连接信息" prop="configStatus">
              <el-select v-model="searchValue.configStatus" clearable placeholder="请选择连接信息">
                <el-option label="已配置" :value="1" :key="1" />
                <el-option label="待配置" :value="0" :key="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最近执行时间" prop="startTime">
              <el-date-picker
                v-model="searchValue.startTime"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="text-right">
            <el-button
              @click="search"
              type="primary"
              v-hasPermi="['asset:dataSource-fileServer:search']"
              >搜索</el-button
            >
            <el-button @click="searchReset" plain>重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>

    <ContentWrap>
      <el-form-item>
        <el-button
          @click="add('create', '')"
          type="primary"
          v-hasPermi="['asset:dataSource-fileServer:create']"
          >新增</el-button
        >
        <el-button
          @click="matchCollect('')"
          plain
          :disabled="ids.length == 0"
          v-hasPermi="['asset:dataSource-fileServer:batchCollect']"
        >
          批量采集</el-button
        >
        <el-button
          type="danger"
          plain
          confirm
          @click="batchDelRow"
          :disabled="ids.length == 0"
          v-hasPermi="['asset:dataSource-fileServer:batchDelete']"
        >
          删除</el-button
        >
        <el-button
          plain
          @click="handleExport"
          :disabled="ids.length == 0"
          v-hasPermi="['asset:dataSource-fileServer:export']"
        >
          导出</el-button
        >
        <el-button
          plain
          @click="importDialog = true"
          v-hasPermi="['asset:dataSource-fileServer:import']"
        >
          导入</el-button
        >
        <el-button
          plain
          @click="handleBatchAdd"
          v-hasPermi="['asset:dataSource-fileServer:batchAdd']"
        >
          批量新增</el-button
        >
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>

    <BatchDynamicDialog
      source="fileSource"
      :dialogVisible="batchAddDialog"
      @close="close"
      v-if="batchAddDialog"
    />
    <ImportSource
      :systemList="systemList"
      :options="options"
      :dialogVisible="importDialog"
      @close="closeImport"
      v-if="importDialog"
      :datasourceType="2"
    />
  </div>
</template>

<script setup lang="tsx">
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import * as api from '@/api/dataSourceManage/index'
import { useRouter } from 'vue-router'
import { getSimpleDeptList } from '@/api/system/dept'
import { handleTree } from '@/utils/tree'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { Hide, View } from '@element-plus/icons-vue'
import download from '@/utils/download'
import { sysFilterMethod } from '@/utils/selectFilter'
import BatchDynamicDialog from '@/views/asset/components/BatchDynamicForm.vue'
import ImportSource from '../components/ImportSource.vue'
const systemList = ref([])
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const router = useRouter()
const ids = ref<string[]>([])
const matchInfo = ref([])
const sameDepSys = ref({ systems: [], departments: [] })
const assetTypeList = ref([])
const dialogVisible = ref(false)
const batchAddDialog = ref()
const importDialog = ref(false)
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const handleBatchAdd = () => {
  batchAddDialog.value = true
}
const options = ref<Tree[]>([])
const searchReset = () => {
  formRef.value.resetFields()
  search()
}

const fetchData = async ({ page, pageSize }) => {
  const { data, count } = await api.getDataSourceList({
    page,
    pageSize,
    ...searchValue.value,
    datasourceType: 2
  })
  return { data, count }
}
const searchValue = ref({
  name: '',
  ip: '',
  assetType: '',
  deptId: '',
  sysId: '',
  configStatus: '',
  startTime: []
})

/**
 * @description: 跳转至数据采集页面
 */
const matchCollect = (row) => {
  if (row) {
    router.push({
      path: '/asset/addDataCollectTask',
      query: {
        tableData: JSON.stringify(row),
        dataType: 'file',
        inner: 'source'
      }
    })
  } else {
    const isSameDep = sameDepSys.value.departments.every(
      (value) => value === sameDepSys.value.departments[0]
    )
    const isSameSys = sameDepSys.value.systems.every(
      (value) => value === sameDepSys.value.systems[0]
    )
    if (!isSameDep || !isSameSys) {
      ElMessage.error('请选择同一机构同一系统的资产')
      return
    }
    router.push({
      path: '/asset/addDataCollectTask',
      query: {
        tableData: JSON.stringify(matchInfo.value),
        dataType: 'file',
        inner: 'source'
      }
    })
  }
}
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

const close = (isAdd) => {
  batchAddDialog.value = false
  isAdd && search()
}
const closeImport = (isAdd) => {
  importDialog.value = false
  isAdd && search()
}
/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  matchInfo.value = []
  sameDepSys.value.departments = []
  sameDepSys.value.systems = []
  val.map((item) => {
    ids.value.push(item.id)
    matchInfo.value.push(item)
    sameDepSys.value.departments.push(item.deptId)
    sameDepSys.value.systems.push(item.sysId)
  })
}
const handleShowIp = (row) => {
  row.isShowIp = !row?.isShowIp
}
const tableInfo = reactive({
  columns: [
    {
      type: 'selection'
    },
    {
      label: '数据源名称',
      prop: 'name',
      'min-width': '100px'
    },
    {
      label: '资产IP:端口',
      width: '170px',
      render: ({ row }) => {
        return (
          <>
            <div style="display:flex;align-items:center;justify-content:space-between;">
              {row?.isShowIp ? (
                <span>{row.port ? row.ip + ':' + row.port : row.ip}</span>
              ) : (
                <span style="font-size:17px">***********</span>
              )}
              {row?.isShowIp ? (
                <el-icon>
                  <Hide onClick={() => handleShowIp(row)} />
                </el-icon>
              ) : (
                <el-icon>
                  <View onClick={() => handleShowIp(row)} />
                </el-icon>
              )}
            </div>
          </>
        )
      }
    },
    {
      label: '资产类型',
      render({ row }) {
        return (
          <>
            <span>{row.assetTypeName || row.assetType}</span>
          </>
        )
      }
    },

    {
      label: '归属机构',
      prop: 'department'
    },
    {
      label: '归属系统',
      prop: 'system'
    },
    {
      label: '最近扫描时间',
      width: '170px',
      prop: 'scanTime'
    },
    {
      label: '连接信息',
      render: ({ row }) => {
        return <span>{row.configStatus === 1 ? '已配置' : '待配置'}</span>
      }
    },
    {
      label: '操作项',
      width: '230px',
      render: ({ row }) => {
        return (
          <>
            <el-button
              link
              type="primary"
              onClick={() => {
                matchCollect(row)
              }}
              size="small"
              v-hasPermi={[['asset:dataSource-fileServer:singleCollect']]}
            >
              数据采集
            </el-button>
            <el-button
              link
              type="primary"
              onClick={() => {
                collectHistory(row)
              }}
              size="small"
              v-hasPermi={[['asset:dataSource-fileServer:history']]}
            >
              采集历史
            </el-button>
            <el-button
              link
              type="primary"
              onClick={() => {
                add('edit', row)
              }}
              size="small"
              v-hasPermi={[['asset:dataSource-fileServer:edit']]}
            >
              编辑
            </el-button>
            <ns-button
              link
              type="danger"
              confirm
              onClick={() => {
                del(row)
              }}
              style="margin-left:6px"
              size="small"
              v-hasPermi={[['asset:dataSource-fileServer:singleDelete']]}
            >
              删除
            </ns-button>
          </>
        )
      }
    }
  ],
  data: []
})
const del = (row) => {
  api.deleteDataSource({ idList: [row.id] }).then(({ code }) => {
    code === 200 && ElMessage.success('删除成功')
    code === 200 && search()
  })
}
//导出
const handleExport = async () => {
  proxy?.$modal
    .confirm(`确定要导出所选数据吗？`)
    .then(async () => {
      const data = await api.exportDataSource({ ids: ids.value, datasourceType: 2 })
      download.excel(data, '文件服务器导出.xlsx')
    })
    .catch(() => {})
}

const add = (type: string, row) => {
  proxy?.$Drawer({
    title: type === 'create' ? '添加资产' : '编辑资产',
    component: import('@/views/asset/components/Database.vue'),
    size: '60%',
    params: {
      type,
      isAdd: type === 'create' ? true : false,
      source: 'fileSource',
      info: row,
      callBack: () => {
        ElMessage.success('新建成功')
        search()
      }
    }
  })
}
const collectHistory = (row) => {
  router.push({
    path: '/asset/fileServerResult',
    query: {
      datasourceId: row.id,
      datasourceType: row.datasourceType
    }
  })
}

function batchDelRow() {
  proxy.$modal
    .confirm(`确定要删除所选数据吗？`)
    .then(() => {
      api.deleteDataSource({ idList: ids.value }).then(({ code }) => {
        code === 200 && ElMessage.success('删除成功')
        code === 200 && search()
        if (code === 200) {
          ids.value = []
        }
      })
    })
    .catch(() => {})
}
onMounted(() => {
  getSimpleDeptList().then((res) => {
    options.value = res
  })
  api.getAssetTypeList({ datasourceType: 2 }).then((res) => {
    assetTypeList.value = res
  })
  getSimpleSystemList().then((res) => {
    systemList.value = handleTree(res, 'id', 'pid')
  })
})
</script>

<style lang="scss">
.file-server {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  .el-cascader {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
